package com.bbs.core.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.bbs.core.common.WebUtils;
import com.bbs.core.model.Post;
import com.bbs.core.model.Topic;
import com.bbs.core.model.User;
import com.bbs.core.service.MessageService;
import com.bbs.core.service.PostService;
import com.bbs.core.service.TopicService;

@Controller
public class PostController {
	
	@Autowired
	private PostService postService;
	
	@Autowired
	private TopicService topicService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	WebUtils webUtils;
	
	@ResponseBody
	@RequestMapping("/bbs/post/save")
	public JSONObject savePost(Post post, HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject result = new JSONObject();
		result.put("err", 1);
		if(post.getContent().length()<5){
			result.put("msg", "内容太短，请重新编辑！");
		}else{
			post.setHasReply("0");
			post.setCreateTime(new Date());
			User user =  webUtils.currentUser(request, response);
			postService.savePost(post,user);
			Topic topic = topicService.getTopicByPrimaryKey(post.getTopicId());
			int totalPost = topic.getPostCount() + 1;
			topic.setPostCount(totalPost);
			topicService.updateTopic(topic);
			
			messageService.notifyParticipant(topic.getId(),user.getId());
			
			int pageSize = 6;
			int page = (totalPost/pageSize)+(totalPost%pageSize==0?0:1);
			result.put("msg", "/bbs/topic/"+post.getTopicId()+"-"+page+".html");
			result.put("err", 0);
		}
		return result;
	}

}
